package com.ruoyi.carShopService.controller;

import com.ruoyi.carShopService.service.LoginService;
import com.ruoyi.carShopService.util.JwtUtil;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.system.api.domain.CarMerchantPrincipal;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @author yang
 * @version 1.0
 * @data 2024/9/12 15:37
 */
@RestController
public class LoginController {

    @Autowired
    private RedisTemplate  redisTemplate;

    @Autowired
    private LoginService loginService;



    // 生成短信
    @RequestMapping("/createLoginSms")
    public Map createSms(String phoneNumber) {
        return loginService.createSms(phoneNumber);
    }

    // 登录
    @RequestMapping("/login")
    public AjaxResult login(@RequestParam("phoneNumber") String phoneNumber,@RequestParam("code") String code) {

        String str = (String) redisTemplate.opsForValue().get(phoneNumber);
        if( str == null){
            return AjaxResult.error("验证码已过期/失效",null);
        }
        if( !str.equals(code) ) {
            return AjaxResult.error("验证码错误",null);
        }

        CarMerchantPrincipal merchant =  loginService.selectByPhoneNumber(phoneNumber);
        if(merchant == null) {
            return AjaxResult.error("商家未注册",null);
        }
        String jwt = JwtUtil.createJWT(merchant.getMpId().toString());
        redisTemplate.delete(phoneNumber);
        return AjaxResult.success("登录成功",jwt);
    }
    // 登录成功后，加载首页信息
    @RequestMapping("/loadInfo")
    public AjaxResult loadInfo(@RequestHeader("token") String token){

        System.out.println(token);

        // 解析token
        try{
            Claims claims = JwtUtil.parseJWT(token);
            String mpId = claims.getSubject();
//            System.out.println(mpId);
            //4 根据mpId查询商家信息
            CarMerchantPrincipal merchant =  loginService.selectByMerchantId(mpId);

//            System.out.println("merchant:" + merchant);
            return AjaxResult.success("加载信息成功",merchant);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }


    }

}
